import axios from 'axios';
import { message } from 'antd';
import type { ApiResponse } from '@/types';

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const { data } = response;
    
    // 如果返回的data有success字段，根据success判断
    if (data && typeof data.success === 'boolean') {
      if (data.success) {
        return response;
      } else {
        message.error(data.message || '请求失败');
        return Promise.reject(new Error(data.message || '请求失败'));
      }
    }
    
    // 如果返回的data有code字段，根据code判断
    if (data && typeof data.code === 'number') {
      if (data.code === 0) {
        return response;
      } else {
        message.error(data.msg || '请求失败');
        return Promise.reject(new Error(data.msg || '请求失败'));
      }
    }
    
    return response;
  },
  (error) => {
    // 处理HTTP错误
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          message.error('登录已过期，请重新登录');
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          message.error('没有权限访问');
          break;
        case 404:
          message.error('请求的资源不存在');
          break;
        case 500:
          message.error('服务器内部错误');
          break;
        default:
          message.error(data?.message || `请求错误: ${status}`);
      }
    } else if (error.request) {
      message.error('网络错误，请检查网络连接');
    } else {
      message.error('请求失败');
    }
    
    return Promise.reject(error);
  }
);

// 通用请求方法
export const request = {
  get: <T = any>(url: string, params?: any): Promise<ApiResponse<T>> => {
    return api.get(url, { params }).then(res => res.data);
  },
  
  post: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return api.post(url, data).then(res => res.data);
  },
  
  put: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return api.put(url, data).then(res => res.data);
  },
  
  delete: <T = any>(url: string): Promise<ApiResponse<T>> => {
    return api.delete(url).then(res => res.data);
  },
  
  upload: <T = any>(url: string, file: File, onProgress?: (percent: number) => void): Promise<ApiResponse<T>> => {
    const formData = new FormData();
    formData.append('file', file);
    
    return api.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(percent);
        }
      },
    }).then(res => res.data);
  },
};

export default api;